/**
 * <p>
 * 描述：
 * </p>

 * @package ：com.andy.demo.soap<br>
 * @author ：wanglongjie<br>
 */
package com.andy.demo.soap;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * 描述：调用Soap工具类
 * </p>
 * 
 * @author wanglongjie<br>
 * @version v1.0 2017年7月28日上午11:04:43
 */
public class SoapCallUtils {
	private static Logger logger = LoggerFactory.getLogger(SoapCallUtils.class);
	/**
	 * 缓冲区
	 */
	private final static int SIZE = 1024 * 100;
	/**
	 * 开始标识
	 */
	private final static String FLAG_Begin = "<return>";
	/**
	 * 结束标识
	 */
	private final static String FLAG_End = "</return>";

	/**
	 * 
	 * <p>
	 * 描述：调用WebService方法
	 * </p>
	 * 
	 * @Date 2017年7月28日上午11:20:23 <br>
	 * @param soapParam
	 *            SoapParam对象实例
	 * @return
	 * @throws Exception
	 */
	public static final String call(SoapParam soapParam) throws Exception {
		InputStream is = null;
		try {
			is = getResponseForInputStream(soapParam);
			if (null == is) {
				throw new Exception("获取响应流失败！");
			}
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			byte[] buffer = new byte[SIZE];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				os.write(buffer, 0, len);
			}
			buffer = os.toByteArray();
			os.flush();
			os.close();
			is.close();
			String result = os.toString("UTF-8");
			logger.info("响应报文：{}", new String[] { result });
			if (result.contains(FLAG_Begin) && result.contains(FLAG_End)) {
				return result.substring(
						result.indexOf(FLAG_Begin) + FLAG_Begin.length(),
						result.indexOf(FLAG_End));
			} else {
				return result;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "调用失败：" + e.getMessage();
		}
	}

	/**
	 * 
	 * <p>
	 * 描述：HTTP调用，获取请求的Soap流
	 * </p>
	 * 
	 * @Date 2017年7月28日上午11:14:41 <br>
	 * @param soapParam
	 *            SoapParam对象实例
	 * @return
	 * @throws Exception
	 */
	private static InputStream getResponseForInputStream(SoapParam soapParam)
			throws Exception {
		String requestBody = SoapRequestBody.requestBody(soapParam);
		logger.info("请求报文：{}", new String[] { requestBody });
		URL url = null;
		InputStream is = null;
		url = new URL(soapParam.getWsdlLocation());
		URLConnection conn = url.openConnection();
		conn.setUseCaches(false);// POST请求 禁用缓存
		conn.setReadTimeout(6000);// 设置请求时间
		conn.setDoInput(true);// 设置从conn读入
		conn.setDoOutput(true);// 设置从conn输出

		conn.setRequestProperty("Content-Length",
				Integer.toString(requestBody.length()));
		conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		conn.setRequestProperty(
				"SOAPAction",
				String.valueOf(soapParam.getInterfaceName()
						+ soapParam.getCallMethodName()));
		OutputStream os = conn.getOutputStream();
		OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
		osw.write(requestBody);
		osw.flush();
		osw.close();
		is = conn.getInputStream();
		return is;
	}

}
